package com.code.penguin.utils;

/**
 * 全局分布式id生成器（SnowFlake算法）
 * 这个算法生成的分布式id确保机器的时钟不能出现回拨，
 * 在分布式场景中，服务器时钟回拨会经常遇到，一般存在10ms之间的回拨；小伙伴们就说这点10ms，
 * 很短可以不考虑吧。但此算法就是建立在毫秒级别的生成方案，一旦回拨，就很有可能存在重复ID。
 *
 * @author xiaoyaowang
 * @see <a href="https://segmentfault.com/a/1190000011282426">分布式id生成器 SnowFlake算法</a>
 * @see <a href="https://mp.weixin.qq.com/s/7RQhCazoLJ-qO7CglZ6b2Q">一线大厂的分布式唯一 ID 生成方案是什么样的</a>
 */
public class SnowFlakeIdUtil {

    /**
     * 工作组id
     */
    private long workerId;

    /**
     * 数据中心id
     */
    private long dataCenterId;

    /**
     * 序列号
     */
    private long sequence;

    private long twepoch = 1288834974657L;

    /**
     * 工作组id的位数
     */
    private long workerIdBits = 5L;

    /**
     * 数据中心的id的位数
     */
    private long dataCenterIdBits = 5L;

    /**
     * 最大工作组id
     */
    private long maxWorkerId = -1L ^ (-1L << workerIdBits);

    /**
     * 最大数据中心的id
     */
    private long maxdataCenterId = -1L ^ (-1L << dataCenterIdBits);

    /**
     * 序列号的位数
     */
    private long sequenceBits = 12L;

    private long workerIdShift = sequenceBits;
    private long dataCenterIdShift = sequenceBits + workerIdBits;
    private long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits;
    private long sequenceMask = -1L ^ (-1L << sequenceBits);

    private long lastTimestamp = -1L;

    /**
     * 单例对象
     */
    private static SnowFlakeIdUtil single = new SnowFlakeIdUtil(1L, 1L, 0L);

    public static SnowFlakeIdUtil getInstance() {
        return single;
    }

    /**
     * 构造函数
     *
     * @param workerId     工作ID (0~31)
     * @param dataCenterId 数据中心ID (0~31)
     */
    private SnowFlakeIdUtil(long workerId, long dataCenterId, long sequence) {
        // sanity check for workerId
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        if (dataCenterId > maxdataCenterId || dataCenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxdataCenterId));
        }
        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
        this.sequence = sequence;
    }

//    public long getWorkerId() {
//        return workerId;
//    }
//
//    public long getdataCenterId() {
//        return dataCenterId;
//    }
//
//    public long getTimestamp() {
//        return System.currentTimeMillis();
//    }

    //    /**
//     * 保证线程安全性
//     *
//     * @return
//     */
//    public synchronized long nextId() {
//        long timestamp = timeGen();
//
//        if (timestamp < lastTimestamp) {
//            System.err.printf("clock is moving backwards.  Rejecting requests until %d.", lastTimestamp);
//            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds",
//                    lastTimestamp - timestamp));
//        }
//
//        if (lastTimestamp == timestamp) {
//            sequence = (sequence + 1) & sequenceMask;
//            if (sequence == 0) {
//                timestamp = tilNextMillis(lastTimestamp);
//            }
//        } else {
//            sequence = 0;
//        }
//
//        lastTimestamp = timestamp;
//        return ((timestamp - twepoch) << timestampLeftShift) |
//                (dataCenterId << dataCenterIdShift) |
//                (workerId << workerIdShift) |
//                sequence;
//    }

    public long nextId() {

        //获取系统当前时间戳
        long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds",
                    lastTimestamp - timestamp));
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }

        lastTimestamp = timestamp;
        return ((timestamp - twepoch) << timestampLeftShift) |
                (dataCenterId << dataCenterIdShift) |
                (workerId << workerIdShift) |
                sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }

    public static String defaultId() {
        return String.valueOf(getInstance().nextId());
    }

}
